#!/bin/sh

. /usr/share/libubox/jshn.sh

network_clients(){
	# we have moved this one to lua implementation
	/usr/lib/ubus/juci/network.lua clients
}

network_load(){
	json_init 
	json_add_int "active_connections" $(cat /proc/sys/net/netfilter/nf_conntrack_count)
	json_add_int "max_connections" $(cat /proc/sys/net/netfilter/nf_conntrack_max)
	json_dump
}

# TODO: this currently depends on kmod-ipt-conntrack. Need to make this generic!
network_nat_table(){
	/usr/lib/ubus/juci/network.lua nat_table
}

network_bridges() {
	$(brctl show | awk -F'\t' '{ # broadcom is stupid (why not write cli utitlities so they are cli friendly?)
		if(FNR==1) continue; 
		if($1 != "") { 
			if(BRNAME != "") { 
				print BRNAME "=" INTERFACES; 
			} 
			BRNAME=$1; 
			INTERFACES=$6; 
		} else { 
			INTERFACES=INTERFACES "," $8; 
		}
	} 
	END { 
		print BRNAME "=" INTERFACES; 
	}'); 
}

network_nameservers(){
	json_init 
	json_add_array "nameservers"; 
	for ns in `awk '/nameserver/{print $2}' /var/resolv.conf.auto`; do
		json_add_string "" $ns; 
	done
	json_close_array
	json_dump
}

case $1 in 
	.methods) 
		echo "clients,load,nameservers,nat_table"; 
		exit 0
		;;
	clients) 
		network_clients
		;;
	load)
		network_load
		;;
	nat_table)
		network_nat_table
		;;
	nameservers)
		network_nameservers
		;;
esac
